/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable no-shadow */
/* eslint-disable no-debugger */
/* eslint-disable react/no-array-index-key */

/**
 * 表单
 * @Author Lianqi
 * @Date 2022-3-22
 * @description V0.2 增加功能：1、表单布局，2、表单字段配置式，3、表单对外提供事件；
 */

import React, { useImperativeHandle, useState, useRef, useCallback } from 'react'
import { Card } from 'antd'
import FormMain from './form/FormMain'
import { MODE } from './config/Constant'

const parseValues = (fields, incomeValues) => {
  const allValues = {}
  fields?.forEach((item) => {
    allValues[item.name] = incomeValues[item.name]
    // allValues[item.name] = null
  })
  return { ...allValues, ...incomeValues}
}

function FCForm(props) {
  const {
    title,
    mode = MODE.EDIT,
    formRef,
    fields,
    initialValues = {},
    extraTopLeft,
    extraTopRight,
    onCancel,
    onFinish = () => {},
    onFinishFailed = () => {},
    onValuesChange = () => {},
    ...restProps
  } = props

  // const initValues = initialValues
  const initValues = parseValues(fields, initialValues)
  const [formMode, setFormMode] = useState(mode)
  const [formData, setFormData] = useState({ ...initValues })
  const realFormRef = useRef('realFormRef')

  const handleFinish = (values) => {
    if (onFinish) {
      // const params = ConversionDate(fields, realFormRef.current.getFieldsValue())
      // onFinish(params)
      onFinish(values)
    }
  }

  const handleFinishFailed = (values, errorFields, outOfDate) => {
    if (onFinishFailed) {
      onFinishFailed(values, errorFields, outOfDate)
    }
  }

  const handleValuesChange = (changedValues, allValues) => {
    setFormData(allValues)
    onValuesChange(changedValues, allValues)
  }

  const doReset = () => {
    realFormRef.current.setFieldsValue({ ...initValues })
  }

  const handleReset = useCallback(() => {
    onCancel ? onCancel() : doReset()
  })

  // 暴露给外部组件的方法
  useImperativeHandle(formRef, () => ({
    getForm: () => realFormRef.current.getForm(),
    getFieldError: (fieldName) => realFormRef.current.getFieldError(fieldName),
    getFieldsError: (nameList) => realFormRef.current.getFieldsError(nameList),
    getFieldsValue: () => realFormRef.current.getFieldsValue(true),
    getFieldValue: (fieldName) => realFormRef.current.getFieldValue(fieldName),
    resetFields: () => {
      doReset()
    },
    setFields: (fields) => {
      // TODO
      realFormRef.current.setFields(fields)
    },
    setFieldValue: (name, value) => realFormRef.current.setFieldValue(name, value),
    setFieldsValue: (values) => {
      // const cValues = parseValues(fields, values)
      realFormRef.current.setFieldsValue({ ...values })
    },
    submit: () => {
      realFormRef.current.submit()
    },
    validateFields: (nameList) => realFormRef.current.validateFields(nameList),
    // 设置模式
    setMode: (mode) => {
      setFormMode(mode)
    },
  }))

  const renderTitle = () => {
    if (!(title || extraTopLeft)) {
      return null
    }
    return (
      <>
        <label>{title}</label>
        <span>{extraTopLeft}</span>
      </>
    )
  }

  return (
    <Card
      title={renderTitle()}
      bordered={false}
      extra={extraTopRight}
      bodyStyle={{ padding: '0px 0px'}}
    >
      <FormMain
        mode={formMode}
        fields={fields}
        initialValues={formData}
        realFormRef={realFormRef}
        {...restProps}
        onFinish={handleFinish}
        onFinishFailed={handleFinishFailed}
        onValuesChange={handleValuesChange}
        onInnerReset={handleReset}
      />
    </Card>
  )
}

export default FCForm

